# coding=utf-8
# -*- coding: UTF-8 -*-
#set FLASK_DEBUG=1
#set FLASK_ENV=development
import json

import sys
sys.path.append("../")
from py.bcosclient_utils import *;

from flask import Flask, Blueprint
from flask import (request,make_response,stream_with_context,Response)
from markupsafe import escape


bp = Blueprint("bcosproxy", __name__, url_prefix='/proxy')
def setResponseHeader(response,origin):
  response.headers["content-type"]="text/json"
  response.headers['Acess-Control-Allow-Origin']=origin
  return response
def getRequestSource(request):
    if request.method == 'POST':
        requestSource = request.form
    else:
        requestSource = request.args
    return requestSource
#
#sample: http://localhost:5000/proxy/rpc?cmd=getBlockByNumber&params=1&params=1
#
origin = "*"
@bp.route("/rpc")
def rpc():
    cmd =""
    try:
        requestSource = getRequestSource(request)
        cmd = requestSource.get("cmd")
        paramlist = requestSource.getlist("params")
    
        print(f"cmd = {cmd},paramlist={paramlist}")
        result = call_rpc(bcos3clent, cmd, paramlist)
        resptext = json.dumps(result, indent=4)
        #raise Exception("testrpcerrr")
    except Exception as e:
        resptext = make_error("-1",cmd,"exception",e);
    response = make_response(resptext)
    response = setResponseHeader(response, origin)
    return response

@bp.route("/contract")
def contract():
    cmd =""
    try:
        requestSource = getRequestSource(request)
        cmd = requestSource.get("cmd")
        name = requestSource.get("name")
        address = requestSource.get("address")
        fn_name = requestSource.get("fn")
        params = requestSource.getlist("params")
        print(f"Contract cmd={cmd},name={name},fn={fn_name},params={params}")
        if cmd == 'call':
            result = call(bcos3clent, name, address, fn_name, params)
        if cmd == 'sendtx':
            result = sendtx(bcos3clent, name, address, fn_name, params)
        print("result is:",result)
        resptext = json.dumps(result, indent=4)
    except Exception as e:
        resptext = make_error("-1",cmd,"exception",e);
    response = make_response(resptext)
    response = setResponseHeader(response, origin)
    return response


@bp.route("/raw")
def raw():
    cmd ="";
    try:
        requestSource = getRequestSource(request)
        cmd = requestSource.get("cmd")
        abistr = requestSource.get("abi")
        name = requestSource.get("name")
        address = requestSource.get("address")
        rawdata = requestSource.get("rawdata")
        abiparser = None
        if name is not None and len(name) > 0:
            abiparser = DatatypeParser(f"contracts/{name}.abi")
        if abistr is not None and len(abistr) > 0:
            abiparser = DatatypeParser()
            abiparser.from_text(abistr)
    
    
        print(f"Contract cmd={cmd},name={name},address={address},rawdata={rawdata},abistr={abistr}")
        fn_name = None
        fn_input = None
        if cmd == "call":
            result = callraw(bcos3clent, address, rawdata, abistr)
            fn_input =rawdata
            func = abiparser.get_func_abi_by_selector(fn_input)
            fn_name = func["name"]
            
            
        if cmd == "sendtx":
            try:
                result = bcos3clent.sendRawTransactionData(rawdata)
                #print("flask sendtx result ",result)
            except Exception as e:
                result = {"ret":-1,"msg":"error"}
                
            #fn_name = "set"
            
        #print(f"raw result cmd {cmd}, result:{result}")
        #print("abiparser",abiparser)
        if abiparser is not None:
            #print(f"ready to parse_tx_result:{cmd},{result}")
            result = parse_tx_result(abiparser, result,fn_name)
        resptext = json.dumps(result, indent=4)

    except Exception as e:
        print("raw excepiton ",e)
        import traceback
        traceback.print_exc()
        resptext = make_error("-1",cmd,"exception",e);
        
    response = make_response(resptext)
    response = setResponseHeader(response, origin)
    return response

